<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2023/6/17
 * Time: 15:07
 */
namespace app\admin\controller;

use app\index\service\DyOpenService;
use app\middleware\AdminCheck;
use think\facade\Db;
use think\facade\Log;

class Order {

    protected $middleware = [
        AdminCheck::class => ['except' 	=> [] ]
    ];



    /**
     *   @SWG\Post(
     *     path="/admin/order/getList",
     *     tags={"后台订单相关"},
     *     summary="获取订单列表",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="pageNo,pageSize",
     *      type="string",
     *      description="pageNo,pageSize"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        validateParam('pageNo,pageSize','pageNo,pageSize');
        $param = input();
        $where[] = ['a.is_pay','=',1];
        //支付的订单号
        if(!empty($param['order_no'])){
            $where[] = ['a.order_no','=',$param['order_no']];
        }
        //城市
        if(!empty($param['city'])){
            $where[] = ['a.city','=',$param['city']];
        }
        //支付的来源是抖音还是微信
        if(!empty($param['pay_type'])){
            $where[] = ['a.pay_type','=',$param['pay_type']];
        }
        if(isset($param['status']) && is_numeric($param['status'])){
            $where[] = ['a.status','=',$param['status']];
        }
        if(!empty($param['pay_at'])){
            $where[] = ['a.pay_at','>=',$param['pay_at'][0]];
            $where[] = ['a.pay_at','<=',$param['pay_at'][1]];
        }

        $db = Db::name('pay_order')
            ->alias('a')
            ->leftJoin('user b','a.user_id=b.id')
            ->leftJoin('cars c','a.car_id=c.id')
            ->leftJoin('car_driver_orders do','do.order_id=a.id and do.is_deleted = 0')
            ->leftJoin('car_drivers d','d.id=do.car_driver_id')
            ->where($where);

        $total = $db->count();
        $offset = makeOffset($param['pageNo'],$param['pageSize']);
        $list = $db
            ->field(['a.*', 'c.car_name', 'c.type_name', 'd.name as driver'])
            ->order('pay_at desc')
            ->limit($offset, $param['pageSize'])
            ->select();

        return success('订单列表',['total'=>$total,'list'=>$list]);
    }

    /**
     * 订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(){
        validateParam('id','id');
        $param = input();
        $where[] = ['a.id','=',$param['id']];

        $db = Db::name('pay_order')
            ->alias('a')
            ->leftJoin('user b','a.user_id=b.id')
            ->leftJoin('cars c','a.car_id=c.id')
            ->leftJoin('car_driver_orders do','do.order_id=a.id and do.is_deleted = 0')
            ->leftJoin('car_drivers d','d.id=do.car_driver_id')
            ->where($where);

        $data = $db
            ->field(['a.*', 'c.car_name', 'c.car_vehicle_code', 'c.type_name', 'd.name as driver', 'd.name as driver_name', 'd.mobile as driver_mobile', 'do.car_no as driver_car_no'])
            ->find();

        return success('订单列表', $data);
    }

    /**
     * @return \think\response\Json
     */
    public function allocationDriver() {
        $data = validateParam('car_driver_id,car_no,order_id','car_driver_id,car_no,order_id');
        $order = Db::name('pay_order')->find($data['order_id']);
        if (empty($order)) {
            return error('订单未找到',[]);
        }
        if ($order['status'] != 10) {
            return error('当前订单不可分配试驾员');
        }
        $driver = Db::name('car_drivers')->find($data['car_driver_id']);
        if (empty($driver)) {
            return error('试驾员未找到',[]);
        }
        if ($driver['status'] != 2) {
            return error('试驾员不可用');
        }

        Db::startTrans();
        try {
            // 新增分配
            Db::name('car_driver_orders')->insert($data);

            // 订单状态扭转为待试驾
            Db::name('pay_order')->where(['id' => $data['order_id']])->save(['status' => 20]);;
            Db::commit();
            return success('分配成功', []);
        }catch (\Exception $e){
            Db::rollback();
            return error($e->getMessage());
        }
    }

    /**
     * @return \think\response\Json
     */
    public function completeTestDriver() {
        $data = validateParam('order_id','order_id');
        $order = Db::name('pay_order')->find($data['order_id']);
        if (empty($order)) {
            return error('订单未找到',[]);
        }

        if ($order['status'] != 20) {
            return error('订单状态异常');
        }

        $driverOrder = Db::name('car_driver_orders')->where(['order_id' => $data['order_id']])->find();
        if (empty($driverOrder)) {
            return error('试驾信息未找到',[]);
        }
        if ($driverOrder['status'] == 1) {
            return error('试驾已完成');
        }

        Db::startTrans();
        try {
            // 更改状态
            Db::name('car_driver_orders')->where(['order_id' => $data['order_id']])->save(['status' => 1]);

            // 订单状态扭转为待评价
            Db::name('pay_order')->where(['id' => $data['order_id']])->save(['status' => 40]);;
            Db::commit();
            return success('操作成功', []);
        }catch (\Exception $e){
            Db::rollback();
            return error($e->getMessage());
        }
    }

    /**
     * 取消订单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderCancel(){
        validateParam('order_id','order_id');
        $orderId = input('order_id');
        $order = Db::name('pay_order')->where('id', $orderId)->find();
        if (empty($order)) {
            return error('订单信息未找到');
        }

        // 判断订单状态
        if ( !in_array($order['status'], [0, 10, 11]) ) {
            return error('当前订单不允许取消');
        }
        $statu = 60;

        // 已支付订单请求退款
        if (in_array($order['status'], [10, 11])) {
            try {
                $refundTradeNo = 'r' . $order['order_no'];
                $refundOutTradeNo = (new DyOpenService())->createRefund($order['order_no'], $refundTradeNo, '用户取消订单', $order['pay_money']);
                if($refundOutTradeNo) {
                    $statu = 70;
                }
            } catch (\Exception $exception) {
                Log::info('refund error:' . $exception->getMessage());
                return error('退款失败，请稍后再试');
            }
        }

        // 更改订单状态
        Db::name('pay_order')->where('id', $orderId)->update(['status' => $statu, 'refund_out_trade_no' => $refundOutTradeNo ?? '']);
        return success('取消成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function openCardUpload(){
        validateParam('order_id','order_id');
        $orderId = input('order_id');
        $order = Db::name('pay_order')->where('id', $orderId)->find();
        if (empty($order)) {
            return error('订单信息未找到');
        }

        // 判断订单状态
        if ( !in_array($order['status'], [10]) ) {
            return error('当前订单不允许');
        }
        $statu = 11;

        // 更改订单状态
        Db::name('pay_order')->where('id', $orderId)->update(['status' => $statu, 'refund_out_trade_no' => $refundOutTradeNo ?? '']);
        return success('开启成功');
    }
}